<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div class="min-h-screen bg-[#F5F5F5] flex flex-col">
    <!-- 顶部导航栏 -->
    <header class="sticky top-0 z-10 bg-white shadow-sm h-16 flex items-center px-4">
      <button class="!rounded-button whitespace-nowrap flex items-center text-[#4A90E2]">
        <el-icon><ArrowLeft /></el-icon>
        <span class="ml-1 text-lg">返回</span>
      </button>
      <h1 class="flex-1 text-center text-2xl font-bold text-gray-800">菜品预订</h1>
      <div class="relative">
        <el-icon class="text-2xl text-[#4A90E2] cursor-pointer">
          <ShoppingCart />
        </el-icon>
        <span
            v-if="cartTotalCount > 0"
            class="absolute -top-2 -right-2 bg-red-500 text-white text-xs rounded-full h-5 w-5 flex items-center justify-center"
        >
        {{ cartTotalCount }}
        </span>
      </div>
    </header>
    <main class="flex-1 pb-20">
      <div class="bg-white rounded-lg shadow-md ">
        <!-- 父级分类导航 -->
        <div class="bg-[#4A90E2] px-6 py-4">
          <div class="flex items-center space-x-8">
            <div
                v-for="(parent, index) in parentCategories"
                :key="index"
                class="relative group"
            >
              <div
                  class="flex items-center cursor-pointer"
                  @click="toggleParentCategory(index)"
              >
                <span class="text-white font-medium">{{ parent.name }}</span>
                <el-icon class="ml-2 text-white">
                  <ArrowDown v-if="!parent.expanded" />
                  <ArrowUp v-else />
                </el-icon>
                <span
                    v-if="getSelectedCount(index) > 0"
                    class="ml-2 bg-white text-red-500 rounded-full w-6 h-6 flex items-center justify-center text-xs font-bold"
                >
                {{ getSelectedCount(index) }}
                </span>
              </div>
              <div
                  class="absolute bottom-0 left-0 h-1 bg-white transition-all duration-300"
                  :class="{'w-full': activeParentIndex === index, 'w-0': activeParentIndex !== index}"
              ></div>
            </div>
          </div>
        </div>
        <!-- 子级分类内容 -->
        <div
            v-for="(parent, index) in parentCategories"
            :key="'child-'+index"
            v-show="parent.expanded"
            class="bg-[#F0F8FF] px-6 py-4 transition-all duration-300"
        >
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-medium text-gray-800">{{ parent.name }} 子分类</h3>
            <div class="flex space-x-3">
              <button
                  class="!rounded-button whitespace-nowrap bg-[#4A90E2] text-white px-4 py-2 text-sm"
                  @click="selectAllChildren(index)"
              >
                全选
              </button>
              <button
                  class="!rounded-button whitespace-nowrap bg-gray-200 text-gray-700 px-4 py-2 text-sm"
                  @click="clearAllChildren(index)"
              >
                清除
              </button>
            </div>
          </div>
          <div class="grid grid-cols-4 gap-4">
            <div
                v-for="(child, childIndex) in parent.children"
                :key="childIndex"
                class="rounded-lg p-4 cursor-pointer transition-all duration-200"
                :class="{'bg-[#4A90E2] text-white': child.selected, 'bg-white' : !child.selected}"
                @click="toggleChildSelection(index, childIndex)"
            >
              <div class="flex justify-between items-start">
                <span class="font-medium">{{ child.name }}</span>
                <el-icon v-if="child.selected" class="text-white">
                  <Check />
                </el-icon>
              </div>
              <p class="text-sm mt-2"
                 :title="child.description"
                 :class="{'text-gray-300': child.selected, 'text-gray-500': !child.selected}">
                {{ truncateText(child.description) }}
              </p>
            </div>
          </div>
        </div>
      </div>

      <!-- 日期选择 -->
      <div class="bg-white py-3 px-4 shadow-sm mt-1">
        <div class="flex overflow-x-auto space-x-4">
          <button
              v-for="(date, index) in availableDates"
              :key="index"
              :class="{
                'bg-[#4A90E2] text-white': activeDate === index,
                'bg-gray-100 text-gray-700': activeDate !== index
                }"
              class="!rounded-button whitespace-nowrap flex flex-col items-center py-2 px-4"
              @click="activeDate = index"
          >
            <span class="text-lg">{{ date.day }}</span>
            <span class="text-sm">{{ date.week }}</span>
          </button>
        </div>
      </div>
      <!-- 菜品列表 -->
      <div class="grid grid-cols-2 gap-4 p-4">
        <div
            v-for="(dish, index) in paginatedDishes"
            :key="index"
            class="bg-white rounded-lg shadow-sm overflow-hidden"
        >
          <div class="h-40 overflow-hidden">
            <img
                :src="`${SERVER_ADDR}/upload/${dish.pic}`"
                class="w-full h-full object-cover"
                alt="菜品图片"
            >
          </div>
          <div class="p-3">
            <h3 class="text-xl font-semibold text-gray-800 mb-1">{{ dish.name }}</h3>
            <div class="flex items-center space-x-2">
              <p class="text-gray-500 line-through">¥{{ dish.price }}</p>
              <p class="text-lg text-[#4A90E2] font-bold">¥{{ dish.realPrice }}</p>
            </div>
            <div class="flex items-center justify-between">
              <button
                  class="!rounded-button whitespace-nowrap bg-gray-200 text-gray-700 w-8 h-8 flex items-center justify-center"
                  @click="decreaseDishCount(dish)"
              >
                <el-icon><Minus /></el-icon>
              </button>
              <span class="text-xl font-medium">{{ dish.count }}</span>
              <button
                  class="!rounded-button whitespace-nowrap bg-[#4A90E2] text-white w-8 h-8 flex items-center justify-center"
                  @click="increaseDishCount(dish)"
              >
                <el-icon><Plus /></el-icon>
              </button>
            </div>
          </div>
        </div>
      </div>
      <!-- 分页 -->
      <div class="flex justify-center pb-20">
        <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            layout="prev, pager, next"
            background
        />
      </div>
    </main>
    <!-- 底部购物车栏 -->
    <footer class="fixed bottom-0 left-0 right-0 bg-white shadow-lg h-20 flex items-center px-4">
      <div class="flex items-center">
        <el-icon class="text-2xl text-[#4A90E2] mr-2">
          <ShoppingCart />
        </el-icon>
        <span class="text-lg font-medium">¥{{ cartTotalPrice }}</span>
      </div>
      <div class="flex-1 text-center text-gray-600">
        已选 {{ cartTotalCount }} 件商品
      </div>
      <button
          class="!rounded-button whitespace-nowrap bg-[#4A90E2] text-white py-2 px-6 text-lg"
          @click="showOrder"
      >
        提交订单
      </button>
    </footer>
    <!-- 购物车详情弹窗 -->
    <el-dialog v-model="showCartDetail" title="购物车详情" width="90%">
      <div class="space-y-4">
        <!--预定菜品日期-->
        <div class="flex items-center justify-between">
          <el-date-picker
              v-model="date"
              type="datetime"
              placeholder="请选择预购时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
              date-format="YYYY-MM-DD"
              time-format="HH:mm"
          />
        </div>
        <div
            v-for="(item, index) in cartItems"
            :key="index"
            class="flex items-center justify-between p-3 border-b"
        >
          <div class="flex items-center">
            <img
                :src="`${SERVER_ADDR}/upload/${item.dish.pic}`"
                class="w-16 h-16 object-cover rounded mr-3"
                alt="菜品图片"
            >
            <div>
              <h4 class="text-lg font-medium">{{ item.dish.name }}</h4>
              <p class="text-[#4A90E2]">¥{{ item.dish.realPrice }}</p>
            </div>
          </div>
          <div class="flex items-center">
            <button
                class="!rounded-button whitespace-nowrap bg-gray-200 text-gray-700 w-8 h-8 flex items-center justify-center"
                @click="decreaseDishCount(item.dish)"
            >
              <el-icon><Minus /></el-icon>
            </button>
            <span class="mx-3 text-lg">{{ item.count }}</span>
            <button
                class="!rounded-button whitespace-nowrap bg-[#4A90E2] text-white w-8 h-8 flex items-center justify-center"
                @click="increaseDishCount(item.dish)"
            >
              <el-icon><Plus /></el-icon>
            </button>
          </div>
        </div>
      </div>
      <div class="flex justify-between items-center mt-6 pt-4 border-t">
        <span class="text-xl font-bold">总计: ¥{{ cartTotalPrice }}</span>
        <button
            class="!rounded-button whitespace-nowrap bg-[#4A90E2] text-white py-2 px-6 text-lg"
            @click="submitOrder"
        >
          提交订单
        </button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="js" setup>
import { ref, computed } from 'vue';
import { ArrowLeft, ShoppingCart, Plus, Minus } from '@element-plus/icons-vue';
import goodsApi from "@/api/admin/goodsApi.js";
import categoryApi  from "@/api/admin/categoryApi.js";
import {ElMessage} from "element-plus";
import orderApi from "@/api/user/orderApi.js";
//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
// 日期数据
const availableDates = ref([
  { day: '今天', week: getWeekDay(0) },
  { day: '明天', week: getWeekDay(1) },
  { day: '后天', week: getWeekDay(2) }
]);
// 菜品数据
const dishes = ref([]);
// 购物车数据
const cartItems = ref([]);
// 分页相关
const currentPage = ref(1);
const pageSize = ref(4);
const total = ref(0)
// 活动分类
const activeDate = ref(0);
const showCartDetail = ref(false);
const activeParentIndex = ref(0);
const parentCategories = ref([]);
// 选中的子分类
const selectCategoryIds = ref([]);
// 选中的商品
const goodsIds = computed(()=> {
  return cartItems.value.map(item => {
    const obj = {};
    obj[item.dish.id] = item.count;
    return obj;
  });
})
// 预定时间
const date = ref();
const toggleParentCategory = (index) => {
  parentCategories.value.forEach((cat, i) => {
    cat.expanded = i === index ? !cat.expanded : false;
  });
  activeParentIndex.value = index;
};
const toggleChildSelection = (parentIndex, childIndex) => {
  parentCategories.value[parentIndex].children[childIndex].selected =
      !parentCategories.value[parentIndex].children[childIndex].selected;
  addCategoryIds();
};
const selectAllChildren = (parentIndex) => {
  parentCategories.value[parentIndex].children.forEach(child => {
    child.selected = true;
  });
  addCategoryIds();
};
const clearAllChildren = (parentIndex) => {
  parentCategories.value[parentIndex].children.forEach(child => {
    child.selected = false;
  });
  addCategoryIds();
};
// 加入选中的子分类Id
const addCategoryIds = () => {
  // 将遍历的元素添加到数组中
  selectCategoryIds.value = [];
  parentCategories.value.forEach(item => {
    if (item.children) {
      item.children.forEach(child => {
        if (child.selected) {
          selectCategoryIds.value.push(child.id);
        }
      });
    }
  })
  getAllDishes();
};
const getSelectedCount = (parentIndex) => {
  return parentCategories.value[parentIndex].children.filter(child => child.selected).length;
};
// 隐藏子分类详情
const truncateText = (text) => {
  return text.length > 20 ? text.slice(0, 20) + '...' : text;
};
// 获取所有的父分类
const getParentCategories = () => {
  let category = {
    parentId: 0,
    categoryType: 2,
  };
  categoryApi.selectByPage(null, null, category)
      .then(resp => {
        if (resp.code === 10000){
          parentCategories.value = resp.data;
        }else {
          ElMessage.error(resp.msg)
        }
      })
};
// 获取星期几
function getWeekDay(offset) {
  const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const today = new Date();
  today.setDate(today.getDate() + offset);
  return days[today.getDay()];
}

// 显示订单
const showOrder = () => {
  showCartDetail.value = true;
};
// 提交订单
const submitOrder = () => {
  let orderVo = {
    goodsIds: goodsIds.value,
    date: date.value,
  }
  console.log(orderVo)
  orderApi.insert(orderVo)
      .then(resp => {
        if (resp.code === 10000) {
          ElMessage.success('下单成功！');
          cartItems.value = [];
          date.value = '';
          showCartDetail.value = false;
        }else {
          ElMessage.error(resp.msg)
        }
      })
};

// 获取所有的菜品
const getAllDishes = () => {
  let goods = {
    type: 2,
    categoryIds: selectCategoryIds.value.join(','),
  }
  goodsApi.selectByPage(1, 1000, goods)
      .then(resp => {
        if (resp.code === 10000){
          dishes.value = resp.data.data;
          total.value = resp.data.total;
        }else {
          ElMessage.error(resp.msg)
        }
      })
};
// 分页后的菜品
const paginatedDishes = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return dishes.value.slice(start, end);
});
// 增加菜品数量
const increaseDishCount = (dish) => {
  const item = cartItems.value.find(item => item.dish.id === dish.id);
  if (item) {
    item.count++;
  } else {
    cartItems.value.push({ dish, count: 1 });
  }
};
// 减少菜品数量
const decreaseDishCount = (dish) => {
  const index = cartItems.value.findIndex(item => item.dish.id === dish.id);
  if (index !== -1) {
    if (cartItems.value[index].count > 1) {
      cartItems.value[index].count--;
    } else {
      cartItems.value.splice(index, 1);
    }
  }
};
// 购物车总数量
const cartTotalCount = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.count, 0);
});

// 购物车总价格
const cartTotalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => total + (item.dish.realPrice * item.count), 0);
});
getAllDishes();
getParentCategories();
</script>
<style scoped>
/* 自定义样式 */
.el-dialog {
  border-radius: 12px;
}
.el-dialog__header {
  border-bottom: 1px solid #eee;
  padding: 16px 20px;
  margin-right: 0;
}
.el-dialog__title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}
.el-dialog__body {
  padding: 20px;
}
.el-dialog__footer {
  border-top: 1px solid #eee;
  padding: 16px 20px;
}
.group:hover .text-white {
  background-color: rgba(255, 255, 255, 0.2);
  transition: background-color 0.3s ease;
}
.bg-\[\#F0F8FF\] .grid > div:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
</style>
